/*
 * "@(#)TicketAuction.java	1.35 01/08/15" 
 *
 * Copyright (c) 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

package example.auction;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Vector;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TicketAuction extends MIDlet implements CommandListener {

    Display display;

    Band band = new Band();
    Login       login = new Login();
    TextBox     addBand;
    RmBand      rmBand = new RmBand();
    static final Command BACK_CMD = new Command("Back", Command.BACK, 1);
    static final Command SAVE_CMD = new Command("Save", Command.SCREEN, 2);
    static final Command NEXT_CMD = new Command("Next", Command.SCREEN, 2);
    static final Command SUBMIT_CMD = new Command("Submit", Command.SCREEN, 2);

    List        mainMenu, cateMenu, aucMenu, bandList, ticketList, setMenu;
    Ticker 	ticker;
    Alert       notImpl, savedMsg, alertMsg;
    Form        ticketForm, enterForm, bidForm, submitMsg;
    TextField   enterText, bidText;
    UpdateAlert updateAlert = new UpdateAlert();
    SetDate     date = new SetDate();
    //    SetNumber   number = new SetNumber();
    SetTicker   setTicker = new SetTicker();
    Gauge 	submitGauge;
    Timer TimerService;
    SetMenuForm setMenu2 = new SetMenuForm();
    // Update      updateInt = new Update();

    // Band Name and Index number of the selected band in Band Screen bandList
    String _bandName;
    int    _bandIndex = 0;

    // commands for Band Screen bandList

    static final Command SHOW_CMD = new Command("Show Auctions", 
                                                      Command.SCREEN, 1);
    static final Command ADD_CMD = new Command("Add Bands", 
                                                      Command.SCREEN, 2);
    static final Command RMV_CMD = new Command("Remove Bands",
                                                      Command.SCREEN, 3);
    static final Command SETTING_CMD = new Command("Settings", 
                                                      Command.SCREEN, 4);
    static final Command EXIT_CMD = new Command("Exit", 
                                                      Command.EXIT, 3);
  
    // commands for  Auction Screen ticketList

    static final Command SHOW_INFO_CMD = new Command("More Info",
                                                      Command.SCREEN, 1);
    static final Command MAKE_BID_CMD = new Command("Make a Bid",
                                                      Command.SCREEN, 2);
    static final Command SET_ALERT_CMD = new Command("Set an Alert",
                                                      Command.SCREEN, 3);

    // command for Bid screen ticketForm
    static final Command BAND_CMD = new Command("Bands", 
                                      Command.SCREEN, 1);

    public TicketAuction() {
        display = Display.getDisplay(this);
    }

    public void startApp() {
        notImpl = new Alert("Sorry!!!", "Not Implemented", null, null);

        savedMsg = new Alert(null, "Your new settings have been saved!",
			     null, null);

        alertMsg = new Alert(null, "Your alerts have been saved!",
			     null, null);


        submitGauge = new Gauge("", false, 100, 0);
        submitMsg = new Form("Submitting bid...");
        submitMsg.append(submitGauge);

        ticker = new Ticker("");
        ticker.setString(band.toTickerString(null));

        aucMenu = new List("Auction Menu", Choice.IMPLICIT);
        aucMenu.append("Ticket Info", null);
        aucMenu.append("Make a Bid", null);
        aucMenu.append("Set an Alert", null);
        aucMenu.append("Settings", null);
        aucMenu.append("About", null);
        aucMenu.addCommand(BACK_CMD);
        aucMenu.setCommandListener(this);
        aucMenu.setTicker(ticker);

	// display.setCurrent(aucMenu);

        bandList = new List("Choose Band", Choice.IMPLICIT);
        bandList.addCommand(SHOW_CMD);
        bandList.addCommand(ADD_CMD);
        bandList.addCommand(RMV_CMD);
        bandList.addCommand(SETTING_CMD);
        bandList.addCommand(EXIT_CMD);
        bandList.setCommandListener(this);
        bandList.setTicker(ticker);
        String[] list = band.getList();
        for (int i = 0; i < list.length; i++) {
            bandList.append(list[i], null);
        }
        display.setCurrent(bandList);

        ticketList = new List("dummy", Choice.IMPLICIT);
        ticketList.addCommand(SHOW_INFO_CMD);
        ticketList.addCommand(MAKE_BID_CMD);
        ticketList.addCommand(SET_ALERT_CMD);
        ticketList.addCommand(BACK_CMD);
        ticketList.setCommandListener(this);

        ticketForm = new Form("dummy");
        ticketForm.append("dummy");
        ticketForm.addCommand(BACK_CMD);
        ticketForm.addCommand(BAND_CMD);
        ticketForm.addCommand(MAKE_BID_CMD);
        ticketForm.addCommand(SET_ALERT_CMD);
        ticketForm.setCommandListener(this);

        enterText = new TextField("Tell me when bid reaches:", "", 
                                  10, TextField.NUMERIC);

        enterForm = new Form("Alert");
        enterForm.append(enterText);
        enterForm.addCommand(BACK_CMD);
        enterForm.addCommand(SAVE_CMD);
        enterForm.setCommandListener(this);

	bidText = new TextField("Enter Bid:", "", 10, TextField.NUMERIC);

        bidForm = new Form("dummy");
        bidForm.append("dummy");
        bidForm.append(bidText);
        bidForm.addCommand(BACK_CMD);
        bidForm.addCommand(NEXT_CMD);
        bidForm.setCommandListener(this);

        setMenu = new List("Settings", Choice.IMPLICIT);
        setMenu.append("Ticker Tape", null);
        setMenu.append("Updates", null);
        setMenu.addCommand(BACK_CMD);
        setMenu.setCommandListener(this);
        setMenu.setTicker(ticker);



        addBand = new TextBox("Add Bands, Bands:", "", 100, TextField.ANY);
        addBand.addCommand(BACK_CMD);
        addBand.addCommand(SAVE_CMD);
        addBand.setCommandListener(this);
    }
    public void destroyApp(boolean unconditional) {
    }

    public void pauseApp() {
    }
    public void commandAction(Command c, Displayable s) {

        if (s instanceof List) {
            List obj = (List) s;
            if (obj == aucMenu) {
                if (c == List.SELECT_COMMAND) {
                    int idx = obj.getSelectedIndex();
		    
                    switch (idx) {
                    case 0:
		      // chooseBandType = 0;
                        display.setCurrent(bandList);
                        break;
                    case 1:
		      // chooseBandType = 1;
                        display.setCurrent(bandList);
                        break;
                    case 2:
		      // chooseBandType = 2;
                        display.setCurrent(bandList);
                        break;
                    case 3:
                        display.setCurrent(setMenu);
                        break;
                    case 4:
                        example.About.showAbout(display);
                        break;
			
                    }
                } else if (c == BACK_CMD) {
                    display.setCurrent(bandList);
                }
            } else if (obj == bandList) {
		if (c == List.SELECT_COMMAND || c == SHOW_CMD) {
                    int idx = obj.getSelectedIndex();
                    String bandName = band.getName(idx);
                    ticketList.setTitle(bandName);
                    reconstructList(ticketList, band.getTicketList(bandName));
                    display.setCurrent(ticketList);
		} else if (c == ADD_CMD) {
                    display.setCurrent(addBand);
		} else if (c == RMV_CMD) {
                    display.setCurrent(rmBand);
		} else if (c == SETTING_CMD) {
		    display.setCurrent(setMenu);
		} else if (c == EXIT_CMD) {
                    notifyDestroyed();
                }
            } else if (obj == ticketList) {
                int idx = obj.getSelectedIndex();
                _bandIndex = idx;
	        String bandName = ticketList.getTitle();
		 _bandName = bandName;
                if (c == List.SELECT_COMMAND || c == SHOW_INFO_CMD) {
                    deleteFormItem(ticketForm);
                    ticketForm.setTitle(bandName);
                    band.getTicketData(ticketForm, bandName, idx);
                    display.setCurrent(ticketForm);
                } else if (c == MAKE_BID_CMD) {
                    login.setBandAttributes(ticketList.getTitle(), _bandIndex);
		    login.id.setString(null);
		    login.pd.setString(null);
                    display.setCurrent(login);

                } else if (c == SET_ALERT_CMD) {
                    display.setCurrent(enterForm);
                } else if (c == BACK_CMD) {
                    display.setCurrent(bandList);
                }		
            } else if (obj == setMenu) {
                if (c == List.SELECT_COMMAND) {
                    int idx = obj.getSelectedIndex();
                    switch (idx) {
                    case 0:
			display.setCurrent(setTicker);
                        break;
                    case 1:
			display.setCurrent(setMenu2);
                        break;
                    }
                } else if (c == BACK_CMD) {
                    display.setCurrent(bandList);
                }
            }
        } else if (s instanceof Form) {
            Form obj = (Form) s;
            if (obj == ticketForm) {
                if (c == BACK_CMD) {
		  display.setCurrent(ticketList);
                } else if (c == BAND_CMD) {
                    display.setCurrent(bandList);
                } else if (c == MAKE_BID_CMD) {
		    login.setBandAttributes(ticketList.getTitle(), _bandIndex);
		    login.id.setString(null);
		    login.pd.setString(null);
                    display.setCurrent(login);
                } else if (c == SET_ALERT_CMD) {
                    display.setCurrent(enterForm);
                }

            } else if (obj == bidForm) {
                if (c == BACK_CMD) {
		    login.setBandAttributes(ticketList.getTitle(), _bandIndex);
                    display.setCurrent(login);
                } else if (c == NEXT_CMD) {
		  String bidAmt = bidText.getString();
		  // check if bid text is valid, if not pop up an alert
		  if (bidAmt.equals("")) {
		    Alert errorAlert = 
		      new Alert("Alert", 
				"The bid amount you have entered is invalid.",
				null, AlertType.ERROR);
		    errorAlert.setTimeout(Alert.FOREVER);
		    display.setCurrent(errorAlert);
		  } else {
                      deleteFormItem(login.confirm);
		    login.confirm.append(new StringItem("# "+login.ticketID,
                                                        ""));
                    login.confirm.append(new StringItem(login.bandName, ""));
		    login.confirm.append(new StringItem("Bid Amount:", 
                                                        "$"+bidAmt));
		    display.setCurrent(login.confirm);
		  }
                }
            } else if (obj == enterForm) {
                 if (c == BACK_CMD) {
		    enterText.setString(null);
		    display.setCurrent(bandList);
                } else if (c == SAVE_CMD) {
                    updateAlert.set(ticketList.getTitle(), 
                                    enterText.getString());
                    display.setCurrent(alertMsg, bandList);
                }
            }
        } else if (s instanceof TextBox) {
            TextBox obj = (TextBox) s;
            if (obj == addBand) {
                if (c == BACK_CMD) {
		  // display.setCurrent(setMenu);
		  display.setCurrent(bandList);
                } else if (c == SAVE_CMD) {
                    updateBandList(addBand.getString());
                    display.setCurrent(savedMsg, bandList);
                }
            }
        }
    }


    class Login extends Form implements CommandListener {
        TextField id = new TextField("", "", 10, TextField.ANY);
        TextField pd = new TextField("", "", 10, 
                                     (TextField.NUMERIC|TextField.PASSWORD));
        Form confirm = new Form("Confirm");
        Form notice = new Form("Alert");
        Alert loginAlert = 
	    new Alert("Alert", 
		      "Your must enter your ID and password"
		      + " before you can proceed.",
		      null, null);

        Login() {
            super(null);
            append(new StringItem("Please Enter Auction ID:", ""));
            append(id);
            append(new StringItem("Password:", ""));
            append(pd);
            addCommand(BACK_CMD);
            addCommand(NEXT_CMD);
            setCommandListener(this);

            confirm.append("dummy");
            confirm.addCommand(BACK_CMD);
            confirm.addCommand(SUBMIT_CMD);
            confirm.setCommandListener(this);

            deleteFormItem(notice);
            notice.append(new StringItem("Your bid has been received:", ""));
            notice.append(new StringItem("Confirm #:", "12-B455-31"));
            notice.addCommand(BACK_CMD);
	    notice.addCommand(BAND_CMD);
            notice.setCommandListener(this);
	    loginAlert.setTimeout(Alert.FOREVER);
        }

        String bandName, bid, ticketID, _bandName;
        int _bandIndex;

        void setBid(String bandName, String bid) {
            this.bandName = bandName;
            this.bid = bid;
        }

        void setID(String bandName, String ticketID) {
            this.bandName = bandName;
            this.ticketID = ticketID;
        }

        void setBandAttributes(String bandName, int bandIndex)
	{
	  _bandName = bandName;
	  _bandIndex = bandIndex;
	}

        public void commandAction(Command c, Displayable s) {
            if (s instanceof Form) {
                Form obj = (Form) s;
                if (obj == this) {
                    if (c == BACK_CMD) {
                        display.setCurrent(ticketList);
                    } else if (c == NEXT_CMD) {
		      if ((id.getString().length() == 0) || 
                          (pd.getString().length() == 0)) {
			display.setCurrent(loginAlert);
		      } else {
			login.setID(_bandName, band.getTicketID(_bandName,
                                           _bandIndex));
			bidForm.setTitle(null);
			bidText.setString(null);
                        band.getTicketBidTitle(bidForm, 
                                               _bandName, _bandIndex);
                        bidForm.append(bidText);
			display.setCurrent(bidForm);
		      }

                    }
                } else if (obj == confirm) {
                    if (c == BACK_CMD) {
                        display.setCurrent(bidForm);
                    } else if (c == SUBMIT_CMD) {
                        // display.setCurrent(submitMsg, notice);
			TimerService = new Timer();
			TimerClient timerClient = new TimerClient();
			TimerService.schedule(timerClient, 0, 1000);	
                        display.setCurrent(submitMsg);
                    }
                } else if (obj == notice) {
                    if (c == BACK_CMD) {
                        display.setCurrent(confirm);
                    } else if (c == BAND_CMD) {
		      display.setCurrent(bandList);
                    }
                }
            }
        }
        private class TimerClient extends TimerTask {
            public final void run() {
	 	if (submitGauge.getValue() == submitGauge.getMaxValue()) {
			TimerService.cancel();
			submitGauge.setValue(0);
			display.setCurrent(notice);	
		} else {
			submitGauge.setValue(submitGauge.getValue()+10);
		}	
            }
	}

    }



    class Band {
        private BandListTable table;

        class TicketItem {
            // Ticket info
            String name;   // item name i.e. band name
            String seat;   // seat number
            String sect;   // seat section
            String date;   // concert date
            String place;  // concert place
            String state;  // place's state

            // Bid info
            String id;        // id i.e. item number
            String numItem;   // quantity
            String begBid;    // beginning bid price
            String curBid;    // current bid price
            String incBid;    // bid increment
            String numBids;   // # of bids
            String endsAt;    // Bid close time

            TicketItem(String name,
                       String seat,
                       String sect,
                       String date,
                       String place,
                       String state,
                       String id,
                       String numItem,
                       String begBid,
                       String curBid,
                       String incBid,
                       String numBids,
                       String endsAt) {
                this.name = name;
                this.seat = seat;
                this.sect = sect;
                this.date = date;
                this.place = place;
                this.state = state;
                this.id = id;
                this.numItem = numItem;
                this.begBid = begBid;
                this.curBid = curBid;
                this.incBid = incBid;
                this.numBids = numBids;
                this.endsAt = endsAt;
            }

            TicketItem(String name) {
                this(name, "n/a", "n/a", "n/a", "n/a", "n/a", 
                     "0", "0", "0", "0", "0", "0", "0");
            }
        }

        class BandListTable {
            private Vector vec = new Vector();
            BandListTable() {
                vec = new Vector();
            }
            void put(int nth, Object obj) {
                Object o = null;
                try { 
                    o = vec.elementAt(nth);
                } catch (ArrayIndexOutOfBoundsException e) {
                    o = null;
                }
                if (o == null) {
                    vec.addElement(obj);
                } else {
                    vec.setElementAt(obj, nth);
                }
            }
            Object get(String bandName) {
                int num = vec.size();
                for (int i = 0; i < num; i++) {
                    Object obj = vec.elementAt(i);
                    if (obj instanceof Vector) {
                        Vector v = (Vector) obj;
                        TicketItem item = (TicketItem) v.elementAt(0);
                        if (item.name.equals(bandName)) {
                            return obj;
                        }
                    }
                }
                return null;
            }
            Object elementAt(int index) {
                return vec.elementAt(index);
            }
            void remove(int i) {
                Object o = null;
                try { 
                    o = vec.elementAt(i);
                } catch (ArrayIndexOutOfBoundsException e) {
                    o = null;
                }
                if (o != null) {
                    vec.removeElementAt(i);
                }
            }
            int size() {
                return vec.size();
            }
        }

        Band() {
            table = new BandListTable();
        
            TicketItem t;

            /**
             * 0: Mariah Carey
             */
            t = new TicketItem("Mariah Carey",
                               "18 & 19",
                               "XF, Row 17",
                               "Jun 28, 2001",
                               "PacBell Stadium",
                               "San Francisco, CA",
                               "7720",
                               "2",
                               "45.00",
                               "69.00",
                               "2.00",
                               "3",
                               "11:00 am on Jun 25, 2001");
            add(0, "Mariah Carey", t);

            /**
             * 1: Britney Spears
             */
            t = new TicketItem("Britney Spears",
                               "10",
                               "F9, Row A",
                               "Jun 30, 2001",
                               "Civic Center",
                               "Worchester, MA",
                               "4509",
                               "1",
                               "20.00",
                               "21.00",
                               "1.00",
                               "1",
                               "9:45 pm on Jun 25, 2001");
            add(1, "Britney Spears", t);

            t = new TicketItem("Britney Spears",
                               "69 & 70",
                               "PIT Row 1",
                               "Jul 5, 2001",
                               "Devore Ampitheatre",
                               "Devore, CA",
                               "3058",
                               "2",
                               "9.00",
                               "175.00",
                               "2.50",
                               "40",
                               "9:00 pm on Jun 27, 2001");
            add(1, "Britney Spears", t);

            t = new TicketItem("Britney Spears",
                               "5 & 6 & 7",
                               "PIT Rw 11",
                               "Aug 5, 2001",
                               "Devore Ampitheatre",
                               "Devore, CA",
                               "3541",
                               "3",
                               "28.00",
                               "97.00",
                               "1.00",
                               "11",
                               "11:15 pm on Jul 30, 2001");
            add(1, "Britney Spears", t);

            /**
             * 2: Ricky Martin
             */
            t = new TicketItem("Ricky Martin",
                               "11 & 12",
                               "F Row J",
                               "Jun 8, 2001",
                               "Lakeview Ctr.",
                               "Columbus, OH",
                               "3861",
                               "2",
                               "60.00",
                               "90.00",
                               "5.00",
                               "3",
                               "6:30 pm on Jun 1, 2001");
            add(2, "Ricky Martin", t);

            t = new TicketItem("Ricky Martin",
                               "4 & 6",
                               "N2 Row 5",
                               "Sept 12, 2001",
                               "Smitty Center",
                               "Smith, NJ",
                               "9916",
                               "2",
                               "70.00",
                               "200.00",
                               "10.00",
                               "12",
                               "9:30 pm on Sept 9, 2001");
            add(2, "Ricky Martin", t);

            t = new TicketItem("Ricky Martin",
                               "20 & 22",
                               "KK Row 18",
                               "Sept 14, 2001",
                               "Gaylord Ctr",
                               "Nashville, TN",
                               "3869",
                               "2",
                               "75.00",
                               "110.00",
                               "2.00",
                               "12",
                               "4:00 pm on Sept 9, 2001");
            add(2, "Ricky Martin", t);

            /**
             * 3: Tina Turner
             */
            t = new TicketItem("Tina Turner",
                               "7 & 8",
                               "NN Row 7",
                               "Jan 24, 2002",
                               "Opera House",
                               "Austin, TX",
                               "1313",
                               "2",
                               "60.00",
                               "67.00",
                               "1.00",
                               "7",
                               "5:35 pm on Jan 15, 2002");
            add(3, "Tina Turner", t);

            /**
             * 4: Bruce Springsteen
             */
            t = new TicketItem("Bruce Springsteen",
                               "N & O",
                               "S, Row 14",
                               "Aug 2, 2001",
                               "3COM Park",
                               "San Francisco, CA",
                               "8120",
                               "2",
                               "80.00",
                               "125.00",
                               "2.00",
                               "5",
                               "11:30 am on Jul 26, 2001");
            add(4, "Bruce Springsteen", t);

            /**
             * 5: Red Hot Chili Peppers
             */
            t = new TicketItem("Red Hot Chili Peppers",
                               "3 & 4",
                               "M Row 12",
                               "Oct 18, 2001",
                               "Fillmore",
                               "San Francisco, CA",
                               "2255",
                               "2",
                               "90.00",
                               "150.00",
                               "1.00",
                               "7",
                               "7:30 pm on Oct 2, 2001");
            add(5, "Red Hot Chili Peppers", t);
        }

        void add(String bandName) {
            add(table.size(), bandName, new TicketItem(bandName));
        }

        void add(int i, String bandName) {
            add(i, bandName, new TicketItem(bandName));
        }

        void add(int i, String bandName, TicketItem item) {
            Object obj = table.get(bandName);
            Vector vec = (obj == null) ? new Vector() : (Vector) obj;
            vec.addElement(item);
            table.put(i, vec);
        }

        void remove(int i) {
            table.remove(i);
        }

        String[] getList() {
            int num = table.size();
            String seq[] = new String[num];
            for (int i = 0; i < num; i++) {
                Vector vec = (Vector) table.elementAt(i);
                TicketItem item = (TicketItem) vec.elementAt(0);
                seq[i] = item.name;
            }
            return seq;
        }

        String getName(int nth) {
            Vector vec = (Vector) table.elementAt(nth);
            if (vec != null) {
                TicketItem item = (TicketItem) vec.elementAt(0);
                if (item != null) {
                    return item.name;
                }
            }
            return null;
        }

        String[] getTicketList(String bandName) {
            Object obj = table.get(bandName);
            if (obj == null) {
                return null;
            }

            Vector vec = (Vector) obj;
            int num = vec.size();
            String seq[] = new String[num];

            for (int i = 0; i < num; i++) {
                TicketItem item = (TicketItem) vec.elementAt(i);
                seq[i] = new String(
                    "#" + item.id + " $" + item.curBid + "\n" +
                    item.place + ", " + item.state + "\n" +
                    item.sect + "," + item.seat + " ...");
            }

            return seq;
        }

        TicketItem getTicketItem(String bandName, int nth) {
            Object obj = table.get(bandName);
            if (obj == null) {
                return null;
            }
            Vector vec = (Vector) obj;
            return (TicketItem) vec.elementAt(nth);
        }

        String getTicketID(String bandName, int nth) {
            TicketItem item = getTicketItem(bandName, nth);
            if (item == null) {
                return null;
            }
            return item.id;
        }

        String getTicketDataTitle(String bandName, int nth) {
            TicketItem item = getTicketItem(bandName, nth);
            if (item == null) {
                return null;
            }
            return "#" + item.id + " " + item.name;
        }

        void getTicketData(Form form, String bandName, int nth) {
            TicketItem item = getTicketItem(bandName, nth);
            if (item == null) {
                return;
            }
            form.append(new StringItem("Quantity:",  item.numItem));
            form.append(new StringItem("Starts at:", "$"+item.begBid));
            form.append(new StringItem("Current:",   "$"+item.curBid));
            form.append(new StringItem("Bids:",    item.numBids));
            form.append(new StringItem("Ends at:", item.endsAt));
            form.append(new StringItem("Sec:",     item.sect));
            form.append(new StringItem("Seat(s):", item.seat));
            form.append(new StringItem("Date:",    item.date));
            form.append(new StringItem("Place:",   item.place+","+item.state));
        }

        boolean isTicketData(String bandName, String itemID) {
            return (getTicketItem(bandName, itemID) == null) ? false : true;
        }
        
        TicketItem getTicketItem(String bandName, String itemID) {
            Object obj = table.get(bandName);
            if (obj == null) {
                return null;
            }

            Vector vec = (Vector) obj;
            int num = vec.size();

            for (int i = 0; i < num; i++) {
                TicketItem item = (TicketItem) vec.elementAt(i);
                if (item.id.equals(itemID)) {
                    return item;
                }
            }

            return null;
        }

        void getTicketBidTitle(Form f, String bandName, int itemID) {
            TicketItem item = getTicketItem(bandName, itemID);
            long min = stringToLong1000(item.curBid) + 
                stringToLong1000(item.incBid);
            String minBid = long1000ToString(min);

            deleteFormItem(f);

            f.append(new StringItem("Current Bid:",  "$"+item.curBid));
            f.append(new StringItem("Increment:",    "$"+item.incBid));
            f.append(new StringItem("Minimum Bid:",  "$"+minBid));
        }

        String def_ticker = "Ricky Martin 2 tix $90.00 2 tix $110.00"
            + " 2 tix $200.00 Tina Turner 2 tix $65.00";
        String alt_ticker = "Alanis Morisette 2 tix $58.00 4 tix $115.00"
            + " Fiona Apple 2 tix $37.00";

        String toTickerString(boolean[] selected) {
            String s = "";

            if (selected == null) {
                return alt_ticker;
            }

            // Rock Bands
            if (selected[0]) {
                s += def_ticker;
            }
            // Pop
            if (selected[1]) {
            }
            // Country
            if (selected[2]) {
            }
            // Alternative
            if (selected[3]) {
                if (s.length() > 0) {
                    s += " ";
                }
                s += alt_ticker;
            }
            // Jazz
            if (selected[4]) {
            }
            // Classical
            if (selected[5]) {
            }

            return s;
        }

        long stringToLong1000(String s) {
            if (s == null || s.equals("")) {
                return 0;
            }
            try {
                int index = s.indexOf('.');
                if (index == -1)
                    return (long)1000*Integer.parseInt(s);

                long integerPart = 1000*Integer.parseInt(s.substring(0, index));
                String fracString = s.substring(index+1);
                int multBy = 0;
                switch (fracString.length()) {
                case 0:
                    multBy = 0;
                    break;
                case 1:
                    multBy = 100;
                    break;
                case 2:
                    multBy = 10;
                    break;
                case 3:
                    multBy = 1;
                    break;
                }

                long fractionalPart = multBy * Integer.parseInt(fracString);
                return integerPart + fractionalPart;
            } catch (NumberFormatException nfe) {
                return 0;
            }
        }

        String long1000ToString(long l) {
            if (l == 0)
                return "0";
            String s = String.valueOf(l);
            if (s.length() < 4)
                return "0";
            String newStr = s.substring(0, s.length()-3) +"."+ 
                s.substring(s.length()-2);
            return newStr;
        }
    } // end  band

    class RmBand extends List implements CommandListener {
        RmBand() {
            super("Remove Bands", Choice.MULTIPLE);
            String[] list = band.getList();
            for (int i = 0; i < list.length; i++) {
                append(list[i], null);
            }
   	    addCommand(BACK_CMD);
            addCommand(SAVE_CMD);
            setCommandListener(this);
        }
        public void commandAction(Command c, Displayable s) {

            if (c == SAVE_CMD) {		
  		// Make the ChoiceGroup invisible before doing
		// reconstruction
                boolean[] ret = new boolean[size()];
                getSelectedFlags(ret);
	        removeBandList(ret);
                // go back to bandList after save
                display.setCurrent(savedMsg, bandList);
              } else if (c == BACK_CMD) {
                display.setCurrent(bandList);
            }

        }
        void reset() {
            reconstructList(this, band.getList());
        }
        void removeBandList(boolean[] t) {
            int i = t.length;
            while (--i >= 0) {
                if (t[i]) {
                    band.remove(i);
                }
            }
            reconstructList(bandList, band.getList());
            reconstructList(this, band.getList());
        }
    } // end rm band

    class UpdateAlert {
        String band = "", bid = "";
 	Alert soundAlert;
        UpdateAlert() {
            soundAlert = new Alert("Alert", "",
			     null, AlertType.ALARM);
	    soundAlert.setTimeout(Alert.FOREVER);
        }
        void set(String band, String bid) {
            this.band = band;
            this.bid = bid;
        }
        boolean hasDataToUpdate() {
            return ((band != null) && (band != "") &&
                    (bid != null) && (bid != ""));
        }
        void show() {
            // no-op if band & bid aren't set
	    if (hasDataToUpdate()) {
                String s = new String(band + "\n" + 
                                  "ticket bids\n" +
                                  "have reached\n" +
                                  "$" + bid);
                soundAlert.setString(s);
                display.setCurrent(soundAlert);
            }
        }

    }// end UpdateAlert 


    void updateBandList(String list) {
        if (list.length() == 0) {
            return;
        }

        Vector vec = new Vector();
        int fidx = 0;
        while (true) {
            int idx = list.indexOf(',', fidx);
            if (idx == -1) {
                vec.addElement(list.substring(fidx));
                break;
            }
            vec.addElement(list.substring(fidx, idx));
            fidx = idx + 1;
        }

        for (int i = 0; i < vec.size(); i++) {
            String str = (String)vec.elementAt(i);
            int j = 0;
            int len = str.length();
            for (; j < len; j++) {
                if (str.charAt(j) != ' ') {
                    break;
                }
            }
            if (j == len) {
                continue;
            }
            if (j == 0) {
                band.add(str);
            } else {
                band.add(str.substring(j));
            }
        }
        reconstructList(bandList, band.getList());
        rmBand.reset();
    }


    void reconstructList(Choice list, String[] items) {
        int num = list.size();
        while (--num >= 0) {
            list.delete(num);
        }
        for (int i = 0; i < items.length; i++) {
            list.append(items[i], null);
        }
        // list.setSelectedIndex(0, true);
    }


    class SetTicker extends List implements CommandListener {
        SetTicker() {
            super("Ticker Display", Choice.EXCLUSIVE);
            append("Rock", null);
            append("Pop", null);
            append("Country", null);
            append("Alternative", null);
            append("Jazz", null);
            append("Classical", null);
            setSelectedIndex(3, true);
            addCommand(BACK_CMD);
            addCommand(SAVE_CMD);
            setCommandListener(this);
        }
        boolean[] ret = new boolean[6];
        public void commandAction(Command c, Displayable s) {
            if (c == SAVE_CMD) {
                getSelectedFlags(ret);
                String str = band.toTickerString(ret);
                if (str != null) {
                    ticker.setString(str);
                }
                display.setCurrent(savedMsg, setMenu);
            } else if (c == BACK_CMD) {
                display.setCurrent(setMenu);
            }
        }
    }// end SetTicker

    class SetDate extends Form implements CommandListener {
        DateField dateTimeItem = new DateField(null, DateField.DATE_TIME);
        Date      currentDate = new java.util.Date();

        SetDate() {
            super(null);
            append("Use this screen to set the date and time on your"
		   + "phone before submitting bids.\n");
            append(dateTimeItem);
            addCommand(BACK_CMD);
            setCommandListener(this);
        }

        void setDate() {
	  dateTimeItem.setDate(currentDate);
        }

        public void commandAction(Command c, Displayable s) {
            if (s instanceof Form) {
                Form obj = (Form) s;
                if (obj == this) {
		    Date newDate = dateTimeItem.getDate();
		    if (!newDate.equals(currentDate)) {
		        currentDate = newDate;
		    }
                    if (c == BACK_CMD) {
                        display.setCurrent(setMenu2);
                    }
                }
            }
        }
    }// end SetDate


    class SetMenuForm extends Form 
        implements CommandListener, ItemStateListener {

	Gauge gauge = new Gauge("0", true, 40, 0);
	int n = 0;
	int oldValue = 0;

        Timer timerService = new Timer();
        ChoiceGroup cg;

        SetMenuForm() {
            super("Settings");

            cg = new ChoiceGroup("Updates", Choice.EXCLUSIVE);
            cg.append("Continuous", null);
            cg.append("15 minutes", null);
            cg.append("30 minutes", null);
            cg.append("1 hour", null);
            cg.append("3 hours", null);
            append(cg);

            append("\n");
            append("\n");

            /* Set Number */
            append(new StringItem("Set Alert Volume", ""));
            append(gauge);
	    setItemStateListener(this);

            addCommand(BACK_CMD);
            addCommand(SAVE_CMD);
            setCommandListener(this);
        }

        void setNumber(int num) {
	    gauge.setValue(num);
        }

        public void commandAction(Command c, Displayable s) {
            if (c == SAVE_CMD) {
                if (updateAlert.hasDataToUpdate()) {
                    int idx = cg.getSelectedIndex();
                    TimerTask timerClient = new TimerTask() {
                        public final void run() {
			  updateAlert.show();
                        }
                    };
                    switch (idx) {
                    case 0:
                        timerService.schedule(timerClient, 3000);
                        break;
                    case 1:
                        timerService.schedule(timerClient, 3000);
                        break;
                    case 2:
                        timerService.schedule(timerClient, 3000);
                        break;
                    case 3:
                        timerService.schedule(timerClient, 3000);
                        break;
                    case 4:
                        timerService.schedule(timerClient, 3000);
                        break;
                    }
                }
                display.setCurrent(savedMsg, bandList);
            } else if (c == BACK_CMD) {
                display.setCurrent(setMenu);
            }
        }

	public void itemStateChanged(Item item) { 
	    if (item == gauge) {
		int currentValue = gauge.getValue();
		gauge.setLabel(String.valueOf(currentValue));
	    }
	}
    }

    void deleteFormItem(Form f) {
        int num = f.size();
        while (--num >= 0) {
            f.delete(num);
        }
    }
}
